const orderModel = require('../models/orderModel');
const { updateOrderStatus, getOrdersByProduct, getOrdersBySeller, deleteOrder, editOrder } = require('../models/orderModel');


const createOrder = async (req, res) => {
    const { userId, totalPrice, shippingAddress, orderItems, shippingInfo } = req.body;
    try {
        console.log("创建订单");

        const order = await orderModel.createOrder(userId, totalPrice, shippingAddress);
        await orderModel.createOrderItems(order.order_id, orderItems);
        await orderModel.createOrderShipping(order.order_id, shippingInfo);
        // orderId: order.order_id
        console.log("订单创建成功" + order);
        res.status(201).json({ message: '订单创建成功', orderId: order.order_id });
    } catch (error) {
        res.status(500).json({ message: '创建订单失败', error });
    }
};

// 更新订单支付状态
const updateOrderPaymentStatus = async (req, res) => {
    const { orderId, paymentStatus } = req.body;

    try {
        const paymentToOrderStatus = {
            paid: 'confirmed',
            failed: 'cancelled',
        };

        const orderStatus = paymentToOrderStatus[paymentStatus];

        if (!orderStatus) {
            return res.status(400).json({ message: '无效的支付状态' });
        }

        // 调用模型层方法更新订单状态，传递 orderStatus
        const updateResult = await updateOrderStatus(orderId, orderStatus);

        if (updateResult.affectedRows === 0) {
            return res.status(404).json({ message: '订单未找到' });
        }

        res.status(200).json({
            message: '支付状态更新成功',
            orderId,
            orderStatus,
        });
    } catch (error) {
        console.error('支付状态更新失败:', error);
        res.status(500).json({ message: '支付状态更新失败' });
    }
};


// 获取用户所有订单
const getOrderDetails = async (req, res) => {
    const { userId } = req.params;
    try {
        const orders = await orderModel.getOrderDetails(userId);
        res.status(200).json({ orders });
    } catch (error) {
        res.status(500).json({ message: '获取订单详情失败', error });
    }
};


// 获取单个订单详情
const getOrderById = async (req, res) => {
    const { orderId } = req.params;
    try {
        const order = await orderModel.getOrderById(orderId);
        res.status(200).json({ order });
    } catch (error) {
        res.status(500).json({ message: '获取订单详情失败', error });
    }
};






// 获取某个商品所有购买的订单

const getOrdersByProductHandler = async (req, res) => {
    const { productId } = req.params;  // 获取请求参数中的商品ID

    try {
        const orders = await getOrdersByProduct(productId);

        if (orders.length === 0) {
            return res.status(404).json({ message: '没有找到该商品的订单' });
        }

        res.status(200).json(orders);
    } catch (error) {
        console.error('获取商品购买订单失败:', error);
        res.status(500).json({ message: '获取商品购买订单失败' });
    }
};


// 获取商家发布的商品所有购买订单
const getOrdersBySellerHandler = async (req, res) => {
    const { sellerId } = req.params; // 从请求参数中获取商家 ID

    try {
        // 调用模型方法获取订单信息
        const orders = await getOrdersBySeller(sellerId);

        if (orders.length === 0) {
            return res.status(404).json({ message: '没有找到该商家商品的订单' });
        }

        res.status(200).json(orders);
    } catch (error) {
        console.error('获取商家商品购买订单失败:', error);
        res.status(500).json({ message: '获取商家商品购买订单失败' });
    }
};

// //编辑订单

const editOrderHandler = async (req, res) => {
    const { orderId, recipientName, recipientPhone, address } = req.body; // 获取请求体中的字段

    if (!orderId || !recipientName || !recipientPhone || !address) {
        return res.status(400).json({ message: '缺少必要的参数' });
    }

    try {
        const { shippingResult, orderResult } = await editOrder(orderId, recipientName, recipientPhone, address);

        if (shippingResult.affectedRows === 0 || orderResult.affectedRows === 0) {
            return res.status(404).json({ message: '订单或配送信息未找到' });
        }

        res.status(200).json({ success: true, message: '配送信息更新成功' });
    } catch (error) {
        console.error('更新配送信息失败:', error);
        res.status(500).json({ message: '更新配送信息失败' });
    }
};





//删除订单
const deleteOrderHandler = async (req, res) => {
    const { orderId } = req.body; // 获取订单 ID
    console.log(orderId);


    try {
        const result = await deleteOrder(orderId);

        if (result.affectedRows === 0) {
            return res.status(404).json({ message: '订单未找到或已删除' });
        }

        res.status(200).json({ success: true, message: '订单删除成功' });
    } catch (error) {
        console.error('删除订单失败:', error);
        res.status(500).json({ message: '删除订单失败' });
    }
};

// 取消订单
const cancelOrder = async (req, res) => {
    const { orderId } = req.params;
    try {
        const result = await orderModel.cancelOrder(orderId);
        if (result.affectedRows > 0) {
            res.status(200).json({ message: '订单已取消' });
        } else {
            res.status(400).json({ message: '订单取消失败或订单已被处理' });
        }
    } catch (error) {
        res.status(500).json({ message: '订单取消失败', error });
    }
};

// 在现有代码后添加新方法
const getUserOrderList = async (req, res) => {
    try {
        const userId = req.params.userId;
        const status = req.query.status || 'ALL';

        const orders = await orderModel.getUserOrderList(userId, status);
        // 查看团购订单
        const groupbuyOrders = await orderModel.getUserGroupbuyOrderList(userId);
        // console.log('groupbuyOrders:', groupbuyOrders);
        // 处理图片URL,转换为数组
        const formattedOrders = orders.map(order => ({
            ...order,
            product_image: order.product_image ? JSON.parse(order.product_image)[0] : null,
            createTime: new Date(order.created_at).toLocaleString()
        }));

        res.json({
            success: true,
            data: formattedOrders,
            datas: groupbuyOrders
        });
    } catch (error) {
        console.error('获取订单列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取订单列表失败',
            error: error.message
        });
    }
};

module.exports = { cancelOrder, deleteOrderHandler, editOrderHandler, createOrder, updateOrderPaymentStatus, getOrderDetails, getOrderById, getOrdersByProductHandler, getOrdersBySellerHandler, getUserOrderList };
